import { defineStore } from 'pinia'
import { logoutApi } from '@/api/auth'
import { getUserInfoApi } from '@/api/user'
import { resetRouter } from '@/router'
import { store } from '@/store'

import { UserInfo } from '@/api/user/types'

import { useStorage } from '@vueuse/core'

export const useUserStore = defineStore('user', () => {
  const user: UserInfo = {
    roleNames: [],
    perms: [],
  }

  const token = useStorage('accessToken', '')

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function setToken(accessToken: string) {
    token.value = accessToken
  }
  // 获取信息(用户昵称、头像、角色集合、权限集合)
  async function getUserInfo() {
    const { data: res } = await getUserInfoApi()
    if (res.code === 200 && res.success) {
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      Object.assign(user, { ...res.data })
    }
  }
  // 注销
  async function logout() {
    const { data: res } = await logoutApi()
    if (res.code === 200 && res.success) {
      resetStore()
      location.reload() // 清空路由
    }
  }
  /** 清空缓存 */
  function resetStore() {
    resetRouter()
    token.value = ''
    Object.assign(user, { roleNames: [], perms: [] })
  }
  return {
    token,
    user,
    setToken,
    getUserInfo,
    logout,
    resetStore,
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
